package com.example.testapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class PostMethodActivity extends ApplicationActivity{
    private EditText edit_Username;
    private EditText edit_Password;
    private Handler handler;
    private String result = "";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);
        edit_Username = (EditText) findViewById(R.id.username);
        edit_Password = (EditText) findViewById(R.id.password);
        Button login = (Button) findViewById(R.id.login);

        // 登录事件 发送信息与服务器交互
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 当用户名，密码为空时相应提示
                if("".equals(edit_Username.getText().toString())
                        || "".equals(edit_Password.getText().toString())){
                    Toast.makeText(PostMethodActivity.this, "请填写账号或密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                //
                handler = new Handler(){
                    @Override
                    public void handleMessage(Message msg){
                        super.handleMessage(msg);
                        // 如果服务器返回值为 ok 则表示账号和密码输入正确
                        if("ok".equals(result)){
                            // 登录成功
                            Toast.makeText(PostMethodActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(PostMethodActivity.this, "请填写正确的账号和密码", Toast.LENGTH_SHORT).show();
                        }
                    }
                };

                new Thread(new Runnable() {  // 创建一个新线程，用于从网络上获取数据
                    @Override
                    public void run() {
                        send();
                        Message m = handler.obtainMessage();
                        handler.sendMessage(m);
                    }
                }).start();

            }
        });
    }
    public void send() {
        String target = "http://192.168.0.105:8080//example/post.jsp";//要提交的服务器地址
        URL url;
        try {
            url = new URL(target);                                //创建URL对象
            //创建一个HTTP连接
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            urlConn.setRequestMethod("POST");                     //指定使用POST请求方式
            urlConn.setDoInput(true);                             //向连接中写入数据
            urlConn.setDoOutput(true);                            //从连接中读取数据
            urlConn.setUseCaches(false);                          //禁止缓存
            urlConn.setInstanceFollowRedirects(true);             //自动执行HTTP重定向
            urlConn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");         //设置内容类型
            DataOutputStream out = new DataOutputStream(
                    urlConn.getOutputStream());                   //获取输出流
            //连接要提交的数据
            String param = "username="
                    + URLEncoder.encode(edit_Username.getText().toString(), "utf-8")
                    + "&password="
                    + URLEncoder.encode(edit_Password.getText().toString(), "utf-8");
            out.writeBytes(param);         //将要传递的数据写入数据输出流
            out.flush();                   //输出缓存
            out.close();                   //关闭数据输出流
            if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {//判断是否响应成功
                InputStreamReader in = new InputStreamReader(
                        urlConn.getInputStream());                        //获得读取的内容
                BufferedReader buffer = new BufferedReader(in);       //获取输入流对象
                String inputLine = null;
                //通过循环逐行读取输入流中的内容
                while ((inputLine = buffer.readLine()) != null) {
                    result += inputLine;
                }
                in.close();                                                 //关闭字符输入流
            }
            urlConn.disconnect();                                           //断开连接
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
